// pages/mine/index.js
const app = getApp()
import { getCurrentDate, timestampToTime } from '../../utils/week'
import { sign, hasSign, integerLogList } from '../../api/medal.js'
import { formatTime } from '../../utils/util.js'
import { removeObj } from '../../utils/removeObj.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navIndex:3,
    num:0,
    list:[],
    integral_list:[],
    isRequest:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ num: options.num})
  },
  onShow() {
    this.feach()
  },
  feach() {
    let day1 = new Date().valueOf();
    let arr = []//存放生成的列表
    let arr1 = []//存放4天内已签到的列表
    for (let i = -3; i < 4; i++) {
      let newArr = getCurrentDate(new Date(day1 + (24 * 60 * 60 * 1000 * i)));
      arr.push({ eng: newArr[1], num: newArr[0], active:false })
    }

    hasSign().then(res=>{
      arr1 = res.data
      if (arr1.length > 0) { //签到数大于0再匹配 否则不需要匹配
        arr1.forEach((e, iq) => {
          if (new Date().getDate()-new Date(e.signDay).getDate() < 4) {//只匹配到今天
            arr.forEach((q, i) => {
              if (new Date(e.signDay).getDate() == q.num) {
                arr[i].active = true
              }
            })
          }
        })
      }
      this.setData({ list: arr })
    })
    this._integerLogList()
  },
  _integerLogList(){
    integerLogList().then(res=>{
      this.setData({ integral_list: removeObj(res.rows, ['searchValue', 'createBy', 'updateBy', 'updateTime', 'params', 'integerLogId', 'userId', 'nickname'])})
    })
  },
  navIndexChange(e) {
    this.setData({ navIndex: e.currentTarget.dataset.index})
  },
  integral(e){
    if (this.data.navIndex==3){
      this._sign()
    }
  },
  //签到
  _sign(){
    if (!this.data.isRequest & !this.data.list[3].active) {
      this.setData({ isRequest:true})
      sign().then(res => {
        if (res.code == 0) {
          this.setData({ isRequest: false })
          wx.showModal({
            title: '',
            content: '签到成功，积分+60',
            showCancel: false,
            confirmText: "好的",
            confirmColor: '#576B95',
            success: res => {
              if (res.confirm) {
                this.setData({ ['list[3].active']: true })
                this._integerLogList()
              }
            }
          })
        }else{
        wx.showToast({
          title: '提示',
          content:'请刷新重试'
        })
        }
        
      })
    }
  },
  onPullDownRefresh: function () {
    this.feach()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})